// pages/food/selector.js
const { get } = require('../../utils/request');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        keyword: '',
        currentCategory: 'all',
        foods: [],
        page: 1,
        pageSize: 10,
        hasMore: true,
        isLoading: false,
        mode: '', // 'compare' 或 'record'
        compareIndex: undefined // 用于食物对比时标识选择的是第几个食物
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options.keyword) {
            this.setData({
                keyword: decodeURIComponent(options.keyword)
            });
        }
        
        // 设置模式
        if (options.mode) {
            this.setData({
                mode: options.mode,
                compareIndex: options.index !== undefined ? parseInt(options.index) : undefined
            });
        }
        
        this.loadFoods();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.resetAndSearch();
        wx.stopPullDownRefresh();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        this.loadMore();
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    onSearchInput(e) {
        this.setData({
            keyword: e.detail.value
        });
        // 使用防抖处理搜索
        if (this.searchTimer) {
            clearTimeout(this.searchTimer);
        }
        this.searchTimer = setTimeout(() => {
            this.resetAndSearch();
        }, 500);
    },

    changeCategory(e) {
        const category = e.currentTarget.dataset.category;
        this.setData({
            currentCategory: category
        });
        this.resetAndSearch();
    },

    resetAndSearch() {
        this.setData({
            foods: [],
            page: 1,
            hasMore: true
        });
        this.loadFoods();
    },

    async loadFoods() {
        if (this.data.isLoading || !this.data.hasMore) return;

        try {
            this.setData({ isLoading: true });

            const params = {
                page: this.data.page,
                pageSize: this.data.pageSize,
                category: this.data.currentCategory === 'all' ? '' : this.data.currentCategory,
                keyword: this.data.keyword
            };

            const res = await get('/foods', params);
            
            const newFoods = this.data.page === 1 ? 
                res.foods : 
                [...this.data.foods, ...res.foods];

            this.setData({
                foods: newFoods,
                hasMore: res.foods.length === this.data.pageSize,
                page: this.data.page + 1
            });
        } catch (error) {
            wx.showToast({
                title: '加载失败',
                icon: 'none'
            });
        } finally {
            this.setData({ isLoading: false });
        }
    },

    selectFood(e) {
        const food = e.currentTarget.dataset.food;
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2];

        if (this.data.mode === 'compare') {
            // 食物对比模式
            prevPage.setData({
                selectedFood: food,
                compareIndex: this.data.compareIndex
            });
            wx.navigateBack();
        } else {
            // 记录饮食模式
            const foods = prevPage.data.foods || [];
            foods.push({
                ...food,
                amount: 1 // 默认数量为1
            });
            prevPage.setData({ foods });
            
            if (typeof prevPage.calculateNutrition === 'function') {
                prevPage.calculateNutrition();
            }
            wx.navigateBack();
        }
    },

    loadMore() {
        this.loadFoods();
    },

    addCustomFood() {
        wx.navigateTo({
            url: '/pages/food/add'
        });
    }
})